import random

from django import http
from django_redis import get_redis_connection  # 获取对应库的链接
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.verifications.serializers import SmsCodeSerializer  # 序列化器
from libs.captcha.captcha import captcha


class ImageCodeView(APIView):
    def get(self, request, image_id):
        # 生成图片验证码
        text, image_data = captcha.generate_captcha()
        # 保存图片验证码的值
        redis_code = get_redis_connection("code")  # 获取对应库的链接
        redis_code.setex("image_code_%s" % image_id, 300, text)
        # 返回
        response = http.HttpResponse(image_data)  # 接收到图片
        response["Content-Type"] = "image/png"  # 转换类型为png 图片类型
        return response

class SmsCodeView(GenericAPIView):
    serializer_class = SmsCodeSerializer

    def get(self, request, mobile):
        # 获取参数
        dict_data = request.query_params
        # 创建序列化器, 效验
        serializer = self.get_serializer(data=dict_data)
        serializer.is_valid(raise_exception=True)

        # 判断是否频繁发送短信
        redis_conn = get_redis_connection("code")
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            return Response({"errmsg": "频繁发送"}, status=status.HTTP_400_BAD_REQUEST)

        # 发送短信
        sms_code = "%06d" % random.randint(0, 99999)
        print("sms_code = %s" % sms_code)

        # 使用短信sms包
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code)

        # 短信入库
        redis_conn = get_redis_connection("code")
        redis_conn.setex("sms_code_%s" % mobile, 300, sms_code)

        # 标记用户手机号,是否发送过短信
        redis_conn.setex("send_flag_%s" % mobile, 60, True)
        # 返回响应
        return Response(status=status.HTTP_200_OK)
